package com.lixh.sdk.base.literoute

import android.content.Intent
import android.net.Uri
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import com.lixh.sdk.base.literoute.annotations.*
import java.lang.reflect.Method
import java.lang.reflect.Type


/**
 * 默认 的拦截 器 处理 默认的一些 注解
 */
class DefaultInterceptor : Interceptor {


    /**
     * parse method annotation
     *
     * @param annotation
     * @return
     */
    private fun parseMethodAnnotation(wrapper: IntentWrapper, annotation: Annotation) {
        when (annotation) {
            is ClassName -> {
                wrapper.setClassName("", annotation.value.java.name)
            }
            is FragmentName -> {
                wrapper.fragment = annotation.value.java.newInstance() as Fragment
            }
            is Flag -> {
                wrapper.flags = annotation.value
            }
            is Flags -> {
                annotation.value.forEach {
                    wrapper.addFlags(it)
                }
            }
            is Action -> {
                wrapper.action = annotation.value
            }
        }
    }

    override fun intercept(
        proxy: Any?,
        method: Method,
        args: Array<out Any>?,
        wrapper: IntentWrapper,
    ): IntentWrapper {
        val methodAnnotations: Array<Annotation> = method.annotations
        for (annotation in methodAnnotations) {
            parseMethodAnnotation(wrapper, annotation)
        }
        //解析方法参数
        parseMethodParams(wrapper, method, args)
        return wrapper
    }

    private fun parseMethodParams(wrapper: IntentWrapper, mMethod: Method, args: Array<out Any>?) {
        val types: Array<Type> = mMethod.genericParameterTypes
        // 参数名称
        val parameterAnnotationsArray = mMethod.parameterAnnotations
        for (i in types.indices) {
            val parameterAnnotations: Array<Annotation> = parameterAnnotationsArray[i]
            args?.let {
                for (annotation in parameterAnnotations) {
                    when (annotation) {
                        is Param -> {
                            val key = annotation.value
                            //将解析的数据放入Bundle中
                            parseParameter(wrapper, key, it[i])
                        }
                        is Url -> {
                            if (it[i] is Url) {
                                wrapper.data = it[i] as Uri
                            }
                        }
                    }
                }

            }
        }

    }

    private fun parseParameter(intent: Intent, name: String, value: Any) {
        intent.putExtras(bundleOf(name to value))
    }
}